<?php
/**
+-----------------------------------------------------------------------------------------------
* GouGuOPEN [ 左手研发，右手开源，未来可期！]
+-----------------------------------------------------------------------------------------------
* @Copyright (c) 2021~2024 http://www.gouguoa.com All rights reserved.
+-----------------------------------------------------------------------------------------------
* @Licensed 勾股OA，开源且可免费使用，但并不是自由软件，未经授权许可不能去除勾股OA的相关版权信息
+-----------------------------------------------------------------------------------------------
* @Author 勾股工作室 <hdm58@qq.com>
+-----------------------------------------------------------------------------------------------
*/
declare (strict_types = 1);
namespace app\lawcase\controller;

use app\api\BaseController;
use app\lawcase\model\Court;
use app\user\model\Admin as AdminList;
use app\lawcase\model\CaseLawyer;
use app\lawcase\model\CourtPhone;
use app\lawcase\model\Party;
use think\facade\Db;
use think\facade\Request;

class Api extends BaseController
{
    /**
     * 获取当事人委托身份文本
     * @param int $roleType 角色类型值
     * @return string
     */
    protected function getRoleTypeText($roleType)
    {
        $types = [
            1 => '委托人',
            2 => '对方当事人',
            3 => '第三人'
        ];
        
        if (!is_int($roleType)) {
            return '未知角色';
        }
        
        return isset($types[$roleType]) ? $types[$roleType] : '未知角色';
    }
    
    /**
     * 获取诉讼地位文本
     * @param int $partyType 诉讼地位值
     * @return string
     */
    protected function getPartyTypeText($partyType)
    {
        $types = [
            0 => '未知',
            1 => '原告',
            2 => '被告',
            3 => '第三人',
            4 => '上诉人',
            5 => '被上诉人',
            6 => '再审申请人',
            7 => '再审被申请人',
            8 => '申请执行人',
            9 => '被申请执行人'
        ];
        
        if (!is_int($partyType)) {
            return '未知';
        }
        
        return isset($types[$partyType]) ? $types[$partyType] : '未知';
    }
    /**
     * 添加案件关联律师
     * @return \think\response\Json
     */
    public function addLawyer()
    {
        $param = get_params();

        // 检查律师是否已被选择
        $exist = Db::name('lawcase_lawyer')
            ->where('case_id', $param['case_id'])
            ->where('lawyer_id', $param['lawyer_id'])
            ->where('delete_time', 0)
            ->find();
        
        if ($exist) {
            return json(['code' => 1, 'msg' => '该律师已被选择，不能重复添加', 'data' => []]);
        }

        // 组装数据
        $caseLawyer = [
            'case_id' => $param['case_id'],
            'lawyer_id' => $param['lawyer_id'],
            'lawyer_name' => $param['lawyer_name'],
            'lawfirm_id' => $param['lawfirm_id'],
            'lawfirm_name' => $param['lawfirm_name'],
            'create_time' => time()
        ];

        // 写入数据库
        try{
            $id = (new CaseLawyer())->add($caseLawyer);
            return json(['code' => 0, 'msg' => '添加成功', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '添加失败：'.$e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 设置当事人诉讼身份
     * @return \think\response\Json
     */
    public function set_party_relationship()
    {
        $param = get_params();
        
        // 验证参数
        if (empty($param['id']) || empty($param['case_id']) || !isset($param['relationship'])) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        try {
            // 更新当事人诉讼身份
            Db::name('lawcase_party')
                ->where('id', $param['id'])
                ->where('case_id', $param['case_id'])
                ->update([
                    'relationship' => $param['relationship'],
                    'update_time' => time()
                ]);
                
            return json(['code' => 0, 'msg' => '设置成功', 'data' => ['id' => $param['id'],'case_id' => $param['case_id'],'relationship' => $param['relationship'] ]]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '设置失败：'.$e->getMessage(), 'data' => ['id' => $param['id'],'case_id' => $param['case_id'],'relationship' => $param['relationship']]]);

        }
    }
    /**
     * 删除案件关联律师
     * @return \think\response\Json
     */
    public function delLawyer()
    {
        $param = get_params();
        try{
            $id = (new CaseLawyer())->remove($param['lawyer_id'], $param['case_id']);
            return json(['code' => 0, 'msg' => '删除成功', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：'.$e->getMessage(), 'data' => []]);
        }
    }
    /**
     * 获取法院列表
     * @return \think\response\Json
     */
	public function get_court()
    {
        $param = get_params();
		$where = array();
		if (!empty($param['keywords'])) {
			$where[] = ['id|name', 'like', '%' . $param['keywords'] . '%'];
		}
		$where[] = ['delete_time', '=', 0];

		// 分页参数处理
		$page = max(1, (int)($param['page'] ?? 1));
		$limit = min(100, max(1, (int)($param['limit'] ?? 10)));

		$list = Court::where($where)
			->field('id,name')
			->page($page, $limit)
			->select()
			->toArray();

		$count = Court::where($where)->count();
		
		return json([
			'code' => 0,
			'msg' => '',
			'totalRow' => ['total' => $count],
			'count' => $count,
			'data' => $list
		]);
    }

    /**
     * 获取指定法院电话列表
     * @return \think\response\Json
     */
    public function get_court_phones()
    {
        $param = get_params();
        $court_id = $param['court_id'] ?? 0;

        $list = CourtPhone::where('court_id', $court_id)->select()->toArray();

        return json([
            'code' => 0,
            'msg' => '',
            'data' => $list
        ]);
    }

    /**
     * 获取案件关联律师列表
     * @return \think\response\Json
     */
    public function get_lawyers()
    {
        $caseId = input('case_id/d',0);
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        if(empty($caseId)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $query = Db::name('lawcase_lawyer')
            ->where('case_id', $caseId)
            ->where('delete_time', 0);

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return json([
			'code' => 0,
			'msg' => '',
			'totalRow' => ['total' => $total],
			'count' => $total,
			'data' => $list
		]);
    }

    /**
     * 获取所有在职律师列表
     * @return \think\response\Json
     */
    public function get_all_lawyers()
    {
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        $query = AdminList::alias('a')
				->with('departments')
				->field('a.id as lawyer_id, a.name as lawyer_name, a.did as lawfirm_id, d.title as lawfirm_name')
				->join('Department d', 'd.id = a.did','left')
				->where('a.status',1)
                ->where('d.title', 'like', '%事务所')
				->order('a.id desc');
        $total = $query->count();
        $list = $query->page($page, $limit)->select();
        $total = $query->count();
        $list = $query->page($page, $limit)->select();
        return json([
			'code' => 0,
			'msg' => '',
			'totalRow' => ['total' => $total],
			'count' => $total,
			'data' => $list
		]);
    }

    /**
     * 获取案件进度记录
     * @return \think\response\Json
     */
    public function get_progress()
    {
        $caseId = input('case_id/d',0);
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        if(empty($caseId)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $query = Db::name('oa_lawcase_progress')
            ->alias('p')
            ->join('admin a','p.operator = a.id')
            ->field('p.id,p.type,p.create_time,p.content,a.name as operator_name')
            ->where('p.case_id',$caseId)
            ->where('p.delete_time',0)
            ->order('p.create_time','desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return json([
            'code' => 1,
            'msg' => 'success',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
    
    /**
     * 设置当事人角色
     * @return \think\response\Json
     */
    public function set_party_role()
    {
        $param = get_params();
        
        if(empty($param['id']) || empty($param['case_id'])){
            return json(['code'=>1, 'msg'=>'缺少当事人ID或案件ID']);
        }
        if(empty($param['is_client'])){
            return json(['code'=>1, 'msg'=>'请选择委托身份']);
        }
        
        try{
            Db::name('lawcase_party')
                ->where('id', $param['id'])
                ->where('case_id', $param['case_id'])
                ->update(['is_client' => $param['is_client']]);
                
            return json(['code'=>0, 'msg'=>'设置成功', 'data'=>[]]);
        } catch (\Exception $e) {
            return json(['code'=>1, 'msg'=>'设置失败：'.$e->getMessage()]);
        }
    }
    
    /**
     * 获取当事人关联案件列表
     * @return \think\response\Json
     */
    public function get_party_lawcases()
    {
        $partyId = input('party_id/d',0);
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        if(empty($partyId)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $query = Db::name('lawcase_party')
            ->alias('lp')
            ->join('lawcase l','lp.case_id = l.id')
            ->leftJoin('court c', 'c.id = l.court_id')
            ->leftJoin('case_cause lc', 'lc.id = l.case_cause_id')
            ->leftJoin('lawcase_lawyer ll', 'll.case_id = l.id AND ll.is_main = 1')
            ->leftJoin('admin a', 'a.id = ll.lawyer_id')
            ->group('l.id')  // 按案件ID分组
            ->field('l.id,l.case_code as case_code,c.name as court_name,lc.name as case_cause_name,l.stage,l.status as status,a.name as lawyer_name,l.update_time')
            ->where('lp.party_id',$partyId)
            ->where('lp.delete_time',0)
            ->where('l.delete_time',0)
            ->order('l.update_time','desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select();
        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
    
    /**
     * 获取所有当事人列表
     * @return \think\response\Json
     */
    public function get_all_partys()
    {
        $page = input('page/d',1);
        $limit = input('limit/d',15);
        $keywords = input('keywords/s','');

        $query = Db::name('party')
            ->where('delete_time',0);
            
        if(!empty($keywords)){
            $query->where('name','like','%'.$keywords.'%');
        }

        $total = $query->count();
        $list = $query->page($page, $limit)->select()->each(function($item) {
            // 拼接完整地址
            $item['full_address'] = $this->getFullAddress(
                $item['pid'], 
                $item['cid'], 
                $item['did'], 
                $item['address']
            );
            //转换当事人类型
            $item['party_type_text'] = self::getTypeText($item['party_type']);
            return $item;
        });

        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
     /**
     * 获取完整地址
     * @param int $province 省ID
     * @param int $city 市ID
     * @param int $district 区ID
     * @param string $address 详细地址
     * @return string
     */
    protected function getFullAddress($province, $city, $district, $address)
    {
        $regionNames = Db::name('region')
            ->where('id', 'in', [$province, $city, $district])
            ->column('name', 'id');
            
        return ($regionNames[$province] ?? '') . 
               ($regionNames[$city] ?? '') . 
               ($regionNames[$district] ?? '') . 
               $address;
    }
    /**
     * 获取当事人类型文本
     * @param int $type 类型值
     * @return string
     */
    protected function getTypeText($type)
    {
        $types = [
            1 => '个人',
            2 => '企业'
        ];
        
        return isset($types[$type]) ? $types[$type] : '未知类型';
    }
    /**
     * 关联案件当事人
     * @return \think\response\Json
     */
    public function link_party_case()
    {
        $caseId = input('case_id');
        $partyId = input('party_id');
        $relationship = input('relationship') ?? '';
        
        // 检查是否已存在关联
        $exist = Db::name('lawcase_party')
            ->where('case_id', $caseId)
            ->where('party_id', $partyId)
            ->where('delete_time', 0)
            ->find();
            
        if ($exist) {
            return json(['code' => 1, 'msg' => '该当事人已关联到此案件，不能重复添加']);
        }
        
        try {
            Db::name('lawcase_party')->insert([
                'case_id' => $caseId,
                'party_id' => $partyId,
                'relationship' => $relationship,
                'create_time' => time()
            ]);
            return json(['code' => 0, 'msg' => '关联成功', 'data' => [
                'case_id' => $caseId,
                'party_id' => $partyId,
                'relationship' => $relationship,
                'create_time' => time()
            ]]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '关联失败：' . $e->getMessage()]);
        }
    }
        /**
     * 解除案件当事人关联
     * @return \think\response\Json
     */
    public function unlink_party_case()
    {
        $id = input('id');
        
        try {
            Db::name('lawcase_party')->where('id', $id)->update(['delete_time' => time()]);
            return json(['code' => 0, 'msg' => '解除关联成功', 'data' => [
                'id' => $id
            ]]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '解除关联失败：' . $e->getMessage()]);
        }
    }
    /**
     * 设置主办律师
     * @return \think\response\Json
     */
    public function setMainLawyer()
    {
        $case_id = input('case_id');
        $lawyer_id = input('lawyer_id');
        
        if (empty($case_id) || empty($lawyer_id)) {
            return json(['code' => 1, 'msg' => '参数错误', 'data' => []]);
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 重置该案件下所有律师为非主办状态
            Db::name('lawcase_lawyer')
                ->where('case_id', $case_id)
                ->update(['is_main' => 0]);
            
            // 设置指定律师为主办状态
            Db::name('lawcase_lawyer')
                ->where('case_id', $case_id)
                ->where('lawyer_id', $lawyer_id)
                ->update(['is_main' => 1]);
            
                //设置案件表中的主办律师ID
                Db::name('lawcase')->where('id', $case_id)->update(['main_lawyer' => $lawyer_id]);           
            Db::commit();
            return json(['code' => 0, 'msg' => '设置成功', 'data' => []]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => '设置失败：' . $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 获取案件关联当事人列表
     * @return \think\response\Json
     */
    public function get_case_parties()
    {
        $caseId = input('case_id/d',0);
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        if(empty($caseId)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $query = Db::name('lawcase_party')
            ->alias('lp')
            ->join('party p', 'p.id = lp.party_id')
            ->field('lp.*, p.name as party_name, p.party_type as party_type, p.id_number, p.contact, p.phone')
            ->where('lp.case_id', $caseId)
            ->where('lp.delete_time', 0);

        $total = $query->count();
        
        $list = $query->page($page, $limit)->select()->each(function($item) {
            $item['is_client_text'] = $this->getRoleTypeText($item['is_client'] ?? 0);
            $item['relationship_text'] = $this->getPartyTypeText((int)$item['relationship'] ?? 0);
            return $item;
        });

        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
    
    /**
     * 获取案件进度列表
     * @return \think\response\Json
     */
    public function get_progress_list()
    {
        $caseId = input('case_id/d',0);
        $page = input('page/d',1);
        $limit = input('limit/d',15);

        if(empty($caseId)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $query = Db::name('lawcase_progress')
            ->alias('p')
            ->join('admin a','p.operator = a.id')
            ->field('p.id,p.event_type,p.event_time, p.create_time,p.content,a.name as operator_name')
            ->where('p.case_id',$caseId)
            ->where('p.delete_time',0)
            ->order('p.create_time','desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
    
    /**
     * 删除案件与当事人关联
     * @return \think\response\Json
     */
    public function del_party_case()
    {
        $param = get_params();
        try{
            $result = Db::name('lawcase_party')
                ->where('id', $param['id'])
                ->where('case_id', $param['case_id'])
                ->update(['delete_time' => time()]);
                
            if($result){
                return json(['code' => 0, 'msg' => '删除成功', 'data' => ['id' => $param['id']], 'case_id' => $param['case_id']]);
            }else{
                return json(['code' => 1, 'msg' => '删除失败']);



            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：'.$e->getMessage()]);
        }
    }
    
    /**
     * 获取案件列表(用于选择器)
     * @return \think\response\Json
     */
    public function get_case_list()
    {
        $page = input('page/d',1);
        $limit = input('limit/d',15);
        $keywords = input('keywords/s','');
        $case_id = input('case_id/d',0);
        $type = input('type/s','');

        $query = Db::name('lawcase')
            ->alias('l')
            ->leftJoin('court c', 'c.id = l.court_id')
            ->leftJoin('case_cause cc', 'cc.id = l.case_cause_id')
            ->leftJoin('lawcase_lawyer ll', 'll.case_id = l.id AND ll.is_main = 1')
            ->leftJoin('admin a', 'a.id = ll.lawyer_id')
            ->field('l.id, l.case_code, c.name as court_name, cc.name as case_cause_name, a.name as lawyer_name')
            ->where('l.delete_time',0);
            
        if(!empty($keywords)){
            $query->where('l.case_code|c.name|cc.name|a.name', 'like', '%'.$keywords.'%');
        }
        
        if(!empty($case_id)){
            $query->where('l.id', $case_id);
        }
        
        if(!empty($type)){
            $query->where('l.type', $type);
        }

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }
    
    /**
     * 获取文档类型列表
     * @return \think\response\Json
     */
    public function get_doctype_list()
    {
        $types = [
            1 => '起诉状',
            2 => '委托代理材料',
            3 => '原被告身份证明',
            4 => '证据目录及证据材料',
            5 => '银行账户确认书',
            6 => '送达地址确认书',
            7 => '裁判文书/调解文书',
            8 => '其他'
        ];
        
        return json([
            'code' => 0,
            'msg' => '',
            'data' => $types
        ]);
    }

    /**
     * 获取案件文档列表
     * @return \think\response\Json
     */
    public function get_casedoc_list()
    {
        $caseId = input('case_id/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        $docType = input('doc_type/d', 0);
        if (empty($caseId) || empty($docType)) {
            return json(['code' => 1, 'msg' => '参数错误：案件ID和文档类型不能为空', 'data' => []]);
        }

        $query = Db::name('case_doc')
            ->alias('d')
            ->join('admin a', 'a.id = d.upload_uid')
            ->field('d.id, d.title, d.doc_type, d.file_ids, d.create_time, d.update_time, a.name as uploader_name')
            ->where('d.case_id', $caseId)
            ->where('d.delete_time', 0);

        if ($docType > 0) {
            $query->where('d.doc_type', $docType);
        }

        $query->order('d.update_time', 'desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select()->each(function($item) {
            // 获取文件信息
            $item['files'] = [];
            if ($item['file_ids']) {
                // 处理file_ids字段，兼容JSON数组和逗号分隔字符串两种格式
                if (is_string($item['file_ids']) && strpos($item['file_ids'], '[') === false) {
                    $fileIds = array_filter(explode(',', $item['file_ids']));
                } else {
                    $fileIds = json_decode($item['file_ids'], true);
                }
                if (is_array($fileIds) && !empty($fileIds)) {
                    $files = Db::name('file')->where('id', 'in', $fileIds)
                        ->field('id,name as filename,filepath,filesize as size,fileext,create_time')
                        ->select()
                        ->toArray();
                    $item['files'] = $files;
                    $item['name'] = $item['title'];
                    $item['size'] = format_bytes(array_sum(array_column($files, 'size')));
                    $item['uploader'] = $item['uploader_name'];
                    $item['file_create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
            }
            // 格式化时间
            $item['create_time_text'] = date('Y-m-d H:i:s', $item['create_time']);
            $item['update_time_text'] = date('Y-m-d H:i:s', $item['update_time']);
            // 格式化文档类型
            $item['doc_type_text'] = $this->getDocTypeText($item['doc_type']);

            return $item;
        });

        return json([
            'code' => 0,
            'msg' => '',
            'totalRow' => ['total' => $total],
            'count' => $total,
            'data' => $list
        ]);
    }

    /**
     * 获取文档类型文本
     * @param int $docType 文档类型值
     * @return string
     */
    protected function getDocTypeText($docType)
    {
        $types = [
            1 => '起诉状',
            2 => '委托代理材料',
            3 => '原被告身份证明',
            4 => '证据目录及证据材料',
            5 => '银行账户确认书',
            6 => '送达地址确认书',
            7 => '裁判文书/调解文书',
            8 => '其他'
        ];
        
        return isset($types[$docType]) ? $types[$docType] : '未知类型';
    }

    /**
     * 获取操作人列表
     * @return \think\response\Json
     */
    public function getOperators()
    {
        try {
            $operators = Db::name('admin')
                ->alias('a')
                ->join('department d', 'a.did = d.id')
                ->field('a.id, a.name')
                ->where('a.status', 1)
                ->where('d.title', 'like', '%法务%')
                ->select();
                
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $operators]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取案件文档信息
     * @return \think\response\Json
     */
    public function get_casedoc_info()
    {
        $id = input('id/d',0);

        if(empty($id)){
            return json(['code'=>0,'msg'=>'参数错误','data'=>[]]);
        }

        $fileInfo = Db::name('file')
            ->where('id',$id)
            ->where('delete_time',0)
            ->find();
            
        if(empty($fileInfo)){
            return json(['code'=>0,'msg'=>'文件不存在','data'=>[]]);
        }

        return json([
            'code' => 0,
            'msg' => '',
            'data' => $fileInfo
        ]);
    }
}
